import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_openim_sdk/flutter_openim_sdk.dart';
import 'package:get/get.dart';
import 'package:openim/pages/contacts/user_profile_panel/user_profile%20_panel_logic.dart';
import 'package:openim_common/openim_common.dart';
import 'package:pull_to_refresh_new/pull_to_refresh.dart';
import 'package:openim/routes/app_navigator.dart';

import '../conversation/conversation_logic.dart';

class GlobalSearchLogic extends CommonSearchLogic {
  final conversationLogic = Get.find<ConversationLogic>();
  final textMessageRefreshCtrl = RefreshController();
  final fileMessageRefreshCtrl = RefreshController();
  final contactsList = <FriendInfo>[].obs;
  final groupList = <GroupInfo>[].obs;
  final textSearchResultItems = <SearchResultItems>[].obs;
  final fileMessageList = <Message>[].obs;
  
  final index = 0.obs;
  final isSearching = false.obs;
  final hasSearched = false.obs;

  final searchFriendOnly = false.obs; // 
  
  final tabs = [
    StrRes.globalSearchAll,
    StrRes.globalSearchContacts,
    StrRes.globalSearchGroup,
    StrRes.globalSearchChatHistory,
    StrRes.globalSearchChatFile,
  ];

  int textMessagePageIndex = 1;
  int fileMessagePageIndex = 1;
  int count = 20;

  @override
  void onInit() {
    final arguments = Get.arguments;
    if (arguments is Map<String, dynamic>) {
      searchFriendOnly.value = arguments['searchFriendOnly'] ?? false; 
    }
    super.onInit();
  }

  switchTab(int index) {
    this.index.value = index;
    if (hasSearched.value && searchKey.isNotEmpty) {
      performSearch();
    }
  }

  // 执行搜索
  void performSearch() async {
    final keyword = searchKey;
    if (keyword.isEmpty) return;

    isSearching.value = true;
    hasSearched.value = true;
    clearList();
    debugPrint('performSearch搜索全部，关键词: $keyword, $searchFriendOnly');

    try {
        if (searchFriendOnly.value) {
        debugPrint('searchFriendOnly搜索联系人，关键词: $keyword');
        await _searchContacts();
        return;
      }
      // 根据当前选中的tab执行相应的搜索
      switch (index.value) {
        case 0: // 全部
          await _searchAll();
          break;
        case 1: // 联系人
          await _searchContacts();
          break;
        case 2: // 群组
          await _searchGroups();
          break;
        case 3: // 聊天记录
          await _searchChatHistory();
          break;
        case 4: // 文件
          await _searchFiles();
          break;
      }
    } catch (e) {
      IMViews.showToast('搜索失败：$e');
    } finally {
      isSearching.value = false;
    }
  }

  // 搜索全部
  Future<void> _searchAll() async {
    await Future.wait([
      _searchContacts(),
      _searchGroups(),
      _searchChatHistory(),
      _searchFiles(),
    ]);
  }

  // 搜索联系人
  Future<void> _searchContacts() async {
    try {
      final friends = await searchFriend();
      contactsList.assignAll(friends);
    } catch (e) {
      print('搜索联系人失败: $e');
    }
  }

  // 搜索群组
  Future<void> _searchGroups() async {
    try {
      final groups = await searchGroup();
      groupList.assignAll(groups);
    } catch (e) {
      print('搜索群组失败: $e');
    }
  }

  // 搜索聊天记录
  Future<void> _searchChatHistory() async {
    try {
      print('开始搜索聊天记录，关键词: $searchKey');
      
      // 清空之前的搜索结果
      textSearchResultItems.clear();
      
      // 执行搜索
      final result = await searchTextMessage();
      
      // 将搜索结果存储到列表中以便UI显示
      if (result.searchResultItems?.isNotEmpty == true) {
        textSearchResultItems.assignAll(result.searchResultItems!);
        print('成功获取搜索结果: ${textSearchResultItems.length} 个会话');
        
        // 打印每个会话的详细信息
        for (var item in textSearchResultItems) {
          print('会话ID: ${item.conversationID}, 消息数量: ${item.messageList?.length ?? 0}');
        }
      } else {
        print('未找到匹配的聊天记录');
      }
      
      print('最终搜索结果: ${textSearchResultItems.length} 个会话');
    } catch (e) {
      print('搜索聊天记录失败: $e');
      if (e is PlatformException) {
        print('平台异常 - 错误代码: ${e.code}');
        print('平台异常 - 错误信息: ${e.message}');
        print('平台异常 - 错误详情: ${e.details}');
      }
      // 确保在出错时清空结果列表
      textSearchResultItems.clear();
    }
  }
  
  Future<void> _searchFiles() async {
    try {
      print('开始搜索文件，关键词: $searchKey');
      
      // 清空之前的搜索结果
      fileMessageList.clear();
      
      // 执行搜索
      final result = await searchFileMessage(pageIndex: 1, count: count);
      
      // 将搜索结果展开为消息列表以便UI显示
      if (result.searchResultItems?.isNotEmpty == true) {
        final messages = result.searchResultItems!
            .expand((item) => item.messageList ?? <Message>[])
            .toList();
        
        fileMessageList.assignAll(messages);
        print('成功获取文件搜索结果: ${messages.length} 条文件消息');
        
        // 打印每条文件消息的详细信息
        for (var message in messages) {
          final fileName = message.fileElem?.fileName ?? '[未知文件]';
          print('文件: $fileName, 发送者: ${message.sendID}');
        }
      } else {
        print('未找到匹配的文件消息');
      }
      
      print('最终文件搜索结果: ${fileMessageList.length} 条消息');
    } catch (e) {
      print('搜索文件失败: $e');
      if (e is PlatformException) {
        print('平台异常 - 错误代码: ${e.code}');
        print('平台异常 - 错误信息: ${e.message}');
        print('平台异常 - 错误详情: ${e.details}');
      }
      // 确保在出错时清空结果列表
      fileMessageList.clear();
    }
  }
  // 清空搜索
  void clearSearch() {
    searchCtrl.clear();
    clearList();
    hasSearched.value = false;
    isSearching.value = false;
  }

  @override
  void clearList() {
    contactsList.clear();
    groupList.clear();
    textSearchResultItems.clear();
    fileMessageList.clear();
  }

  // 打开用户资料
  void openUserProfile(FriendInfo friend) {
    AppNavigator.startUserProfilePane(
      userID: friend.userID!,
      nickname: friend.nickname,
      faceURL: friend.faceURL,
    );
  }

  // 打开群聊
  void openGroupChat(GroupInfo group) {
    final conversationInfo = ConversationInfo(
      conversationID: 'sg_${group.groupID}',
      conversationType: ConversationType.group,
      userID: '',
      groupID: group.groupID,
      showName: group.groupName,
      faceURL: group.faceURL,
    );
    
    AppNavigator.startChat(conversationInfo: conversationInfo);
  }

   // 跳转到消息位置
  void jumpToMessage(Message message) async {
    try {
      // 根据消息类型获取正确的 sourceID 和 sessionType
      String sourceID;
      int sessionType;
      
      if (message.sessionType == ConversationType.single) {
        // 单聊：确定对方用户ID
        sourceID = message.sendID == OpenIM.iMManager.userID 
            ? message.recvID! 
            : message.sendID!;
        sessionType = ConversationType.single;
      }else if (message.sessionType == ConversationType.group || 
                 message.sessionType == ConversationType.superGroup) {
        // 群聊（包括普通群聊和超级群聊）
        sourceID = message.groupID!;
        sessionType = message.sessionType!; // 保持原始的群聊类型
      } else {
        // 其他类型，默认按群聊处理
        sourceID = message.groupID!;
        sessionType = ConversationType.group;
      }
      
      // 通过 SDK 获取正确的 conversationID
      final conversationInfo = await OpenIM.iMManager.conversationManager.getOneConversation(
        sourceID: sourceID,
        sessionType: sessionType,
      );
      
      final conversationID = conversationInfo.conversationID;
      debugPrint('正确的会话ID: $conversationID');
      
      // 跳转到聊天页面并定位到消息
      Get.back(result: {
        'action': 'jumpToMessage',
        'conversationID': conversationID,
        'message': message,
      });
    } catch (e) {
      debugPrint('获取会话信息失败: $e');
      // 如果获取失败，使用原来的逻辑作为备选
      final conversationID = message.sessionType == ConversationType.single
          ? 'si_${message.sendID == OpenIM.iMManager.userID ? message.recvID : message.sendID}'
          : 'sg_${message.groupID}';
      
      Get.back(result: {
        'action': 'jumpToMessage',
        'conversationID': conversationID,
        'message': message,
      });
    }
  }
    // 添加获取用户真实昵称的方法
  Future<String> getRealUserNickname(String userID) async {
    try {
      // 首先尝试从缓存获取
      final cachedUser = UserCacheManager().getUserInfo(userID);
      if (cachedUser?.nickname?.isNotEmpty == true) {
        return cachedUser!.nickname!;
      }

      // 尝试从好友列表获取
      final friendInfo = (await OpenIM.iMManager.friendshipManager.getFriendsInfo(
        userIDList: [userID],
      )).firstOrNull;
      
      if (friendInfo?.nickname?.isNotEmpty == true) {
        return friendInfo!.nickname!;
      }

      // 最后尝试从用户信息获取
      final userInfo = (await OpenIM.iMManager.userManager.getUsersInfoWithCache([userID])).firstOrNull;
      if (userInfo?.nickname?.isNotEmpty == true) {
        return userInfo!.nickname!;
      }

      // 如果都获取不到，返回userID
      return userID;
    } catch (e) {
      print('获取用户昵称失败: $e');
      return userID;
    }
  }

    // 添加获取群聊真实信息的方法
  Future<Map<String, String>> getRealGroupInfo(String groupID) async {
    try {
      // 尝试从SDK获取群组信息
      final groupsInfo = await OpenIM.iMManager.groupManager.getGroupsInfo(
        groupIDList: [groupID],
      );
      
      if (groupsInfo.isNotEmpty) {
        final groupInfo = groupsInfo.first;
        return {
          'groupName': groupInfo.groupName ?? groupID,
          'faceURL': groupInfo.faceURL ?? '',
        };
      }

      // 如果获取不到，返回默认值
      return {
        'groupName': groupID,
        'faceURL': '',
      };
    } catch (e) {
      print('获取群组信息失败: $e');
      return {
        'groupName': groupID,
        'faceURL': '',
      };
    }
  }

  
  Future<void> viewMoreMessages(SearchResultItems searchResult) async {
  if (searchResult.messageList?.isNotEmpty == true) {
    final firstMessage = searchResult.messageList!.first;
    // 根据消息构建会话ID
    final conversationID = firstMessage.sessionType == ConversationType.single
        ? 'si_${firstMessage.sendID == OpenIM.iMManager.userID ? firstMessage.recvID : firstMessage.sendID}'
        : 'sg_${firstMessage.groupID}';
    
    String showName;
    String faceURL = '';
      
    if (firstMessage.sessionType == ConversationType.single) {
      if (firstMessage.sendID == OpenIM.iMManager.userID) {
        // 获取对方真实昵称
        final otherUserID = firstMessage.recvID!;
        showName = await getRealUserNickname(otherUserID);
      } else {
        showName = await getRealUserNickname(firstMessage.sendID!);
        faceURL = firstMessage.senderFaceUrl ?? '';
      }
    } else {
     // 获取群聊真实信息
      final groupInfo = await getRealGroupInfo(firstMessage.groupID!);
      showName = groupInfo['groupName']!;
      faceURL = groupInfo['faceURL']!;
    }
    
    // 构建会话信息 - 修复属性访问错误
    final conversationInfo = ConversationInfo(
      conversationID: conversationID,
      conversationType: firstMessage.sessionType!,
      userID: firstMessage.sessionType == ConversationType.single 
          ? (firstMessage.sendID == OpenIM.iMManager.userID ? firstMessage.recvID : firstMessage.sendID)
          : '',
      groupID: firstMessage.sessionType == ConversationType.group ? firstMessage.groupID : '',
      showName: firstMessage.sessionType == ConversationType.single 
          ? (firstMessage.sendID == OpenIM.iMManager.userID ? '对方' : firstMessage.senderNickname)
          : firstMessage.groupID, // 群组名称需要额外获取
      faceURL: firstMessage.sessionType == ConversationType.single 
          ? (firstMessage.sendID == OpenIM.iMManager.userID ? '' : firstMessage.senderFaceUrl)
          : '', // 群组头像需要额外获取
    );
    
    AppNavigator.startChatHistorySearch(
      conversationID: conversationID,
      conversationInfo: conversationInfo,
    );
  }
}

  // 获取消息显示内容
  String getMessageDisplayContent(Message message) {
    switch (message.contentType) {
      case MessageType.text:
        return message.textElem?.content ?? '';
      case MessageType.atText:
        return message.atTextElem?.text ?? '';
      case MessageType.picture:
        return '[图片]';
      case MessageType.video:
        return '[视频]';
      case MessageType.file:
        return message.fileElem?.fileName ?? '[文件]';
      case MessageType.voice:
        return '[语音]';
      case MessageType.location:
        return '[位置]';
      case MessageType.card:
        return '[名片]';
      case MessageType.merger:
        return '[聊天记录]';
      case MessageType.customFace:
        return '[表情]';
      default:
        return '[未知消息]';
    }
  }

  // 格式化时间显示
  String formatMessageTime(int timestamp) {
    final DateTime messageTime = DateTime.fromMillisecondsSinceEpoch(timestamp);
    final DateTime now = DateTime.now();
    final DateTime today = DateTime(now.year, now.month, now.day);
    final DateTime messageDate = DateTime(messageTime.year, messageTime.month, messageTime.day);
    
    if (messageDate == today) {
      return IMUtils.getChatTimeline(timestamp, 'HH:mm');
    } else if (messageDate == today.subtract(Duration(days: 1))) {
      return '昨天 ${IMUtils.getChatTimeline(timestamp, 'HH:mm')}';
    } else if (messageTime.year == now.year) {
      return '${messageTime.month}月${messageTime.day}日 ${IMUtils.getChatTimeline(timestamp, 'HH:mm')}';
    } else {
      return '${messageTime.year}年${messageTime.month}月${messageTime.day}日 ${IMUtils.getChatTimeline(timestamp, 'HH:mm')}';
    }
  }

  // 高亮搜索关键词
  List<TextSpan> getHighlightedText(String text, String keyword) {
    if (keyword.isEmpty) {
      return [TextSpan(text: text, style: Styles.ts_0C1C33_14sp)];
    }

    final List<TextSpan> spans = [];
    final String lowerText = text.toLowerCase();
    final String lowerKeyword = keyword.toLowerCase();
    
    int start = 0;
    int index = lowerText.indexOf(lowerKeyword);
    
    while (index != -1) {
      // 添加匹配前的文本
      if (index > start) {
        spans.add(TextSpan(
          text: text.substring(start, index),
          style: Styles.ts_0C1C33_14sp,
        ));
      }
      
      // 添加高亮的匹配文本
      spans.add(TextSpan(
        text: text.substring(index, index + keyword.length),
        style: Styles.ts_0089FF_16sp.copyWith(
          backgroundColor: Styles.c_0089FF.withOpacity(0.2),
        ),
      ));
      
      start = index + keyword.length;
      index = lowerText.indexOf(lowerKeyword, start);
    }
    
    // 添加剩余文本
    if (start < text.length) {
      spans.add(TextSpan(
        text: text.substring(start),
        style: Styles.ts_0C1C33_14sp,
      ));
    }
    
    return spans;
  }
}

abstract class CommonSearchLogic extends GetxController {
  final searchCtrl = TextEditingController();
  final focusNode = FocusNode();

  void clearList();

  @override
  void onInit() {
    searchCtrl.addListener(_clearInput);
    super.onInit();
  }

  @override
  void onClose() {
    focusNode.dispose();
    searchCtrl.dispose();
    super.onClose();
  }

  _clearInput() {
    if (searchKey.isEmpty) {
      clearList();
    }
  }

  String get searchKey => searchCtrl.text.trim();

  Future<List<FriendInfo>> searchFriend() => Apis.searchFriendInfo(searchCtrl.text.trim())
      .then((list) => list.map((e) => FriendInfo.fromJson(e.toJson())).toList());

  Future<List<GroupInfo>> searchGroup() => OpenIM.iMManager.groupManager
      .searchGroups(keywordList: [searchCtrl.text.trim()], isSearchGroupName: true, isSearchGroupID: true);

  Future<SearchResult> searchTextMessage({
    int pageIndex = 1,
    int count = 50,
  }) async {
    try {
      print('开始全局搜索文本消息，关键词: $searchKey');
      
      // 直接进行全局搜索，不指定conversationID
      final result = await OpenIM.iMManager.messageManager.searchLocalMessages(
        keywordList: [searchKey],
        messageTypeList: [MessageType.text, MessageType.atText],
        pageIndex: pageIndex,
        count: count,
      );
      
      print('全局搜索结果: totalCount=${result.totalCount}, searchResultItems数量=${result.searchResultItems?.length ?? 0}');
      
      if (result.searchResultItems?.isNotEmpty == true) {
        // 打印详细结果用于调试
        for (var item in result.searchResultItems!) {
          print('会话ID: ${item.conversationID}, 消息数量: ${item.messageList?.length ?? 0}');
          if (item.messageList?.isNotEmpty == true) {
            for (var msg in item.messageList!) {
              final content = msg.textElem?.content ?? msg.atTextElem?.text ?? "";
              print('  消息发送者: ${msg.sendID}, 内容: $content');
            }
          }
        }
        
        return SearchResult(
          totalCount: result.totalCount ?? 0,
          searchResultItems: result.searchResultItems!,
        );
      } else {
        print('未找到匹配的消息');
        return SearchResult(
          totalCount: 0,
          searchResultItems: [],
        );
      }
    } catch (e) {
      print('全局搜索文本消息失败: $e');
      if (e is PlatformException) {
        print('平台异常 - 错误代码: ${e.code}');
        print('平台异常 - 错误信息: ${e.message}');
        print('平台异常 - 错误详情: ${e.details}');
      }
      return SearchResult(
        totalCount: 0,
        searchResultItems: [],
      );
    }
  }

  Future<SearchResult> searchFileMessage({
    int pageIndex = 1,
    int count = 20,
  }) async {
    try {
      print('开始搜索文件消息，关键词: $searchKey');
      
      // 获取所有会话
      final conversations = await OpenIM.iMManager.conversationManager.getAllConversationList();
      final allSearchResults = <SearchResultItems>[];
      int totalCount = 0;
      
      // 逐个搜索每个会话
      for (final conversation in conversations) {
        try {
          final result = await OpenIM.iMManager.messageManager.searchLocalMessages(
            conversationID: conversation.conversationID,
            keywordList: [searchKey],
            messageTypeList: [MessageType.file],
            pageIndex: 1,
            count: count,
          );
          
          if (result.searchResultItems?.isNotEmpty == true) {
            allSearchResults.addAll(result.searchResultItems!);
            totalCount += result.totalCount ?? 0;
          }
        } catch (e) {
          print('搜索会话 ${conversation.conversationID} 的文件消息失败: $e');
        }
      }
      
      print('文件消息搜索结果: ${allSearchResults.length} 个会话，总计 $totalCount 条消息');
      
      return SearchResult(
        totalCount: totalCount,
        searchResultItems: allSearchResults,
      );
    } catch (e) {
      print('搜索文件消息失败: $e');
      return SearchResult(
        totalCount: 0,
        searchResultItems: [],
      );
    }
  }

  String? parseNickname(e) {
    if (e is ConversationInfo) {
      return e.showName;
    } else if (e is GroupInfo) {
      return e.groupName;
    } else if (e is UserInfo) {
      return e.nickname;
    } else if (e is FriendInfo) {
      return e.nickname;
    } else {
      return null;
    }
  }

  String? parseFaceURL(e) {
    if (e is ConversationInfo) {
      return e.faceURL;
    } else if (e is GroupInfo) {
      return e.faceURL;
    } else if (e is UserInfo) {
      return e.faceURL;
    } else if (e is FriendInfo) {
      return e.faceURL;
    } else {
      return null;
    }
  }
}